﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using NLog;
using System;

namespace Atmk.WaterMeter.MIS.Services.Auth
{
    /// <summary>
    /// JWT(json web token)是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准。
    /// JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息，以便于从资源服务器获取资源。
    /// </summary>
    public class JwtHelper
    {
        private static readonly Logger _Logger = LogManager.GetCurrentClassLogger();
        public static string Encode<T>(T payload)
        {
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

                return encoder.Encode(payload, Key);
            }
            catch (Exception ex)
            {
                _Logger.Debug("JWT"+ex.Message);
                    return "";
            }

        }

        public static T Decode<T>(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

                return decoder.DecodeToObject<T>(token, Key, verify: true);
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// 服务端秘钥。令牌加密Key值，项目唯一。
        /// </summary>
        public static string Key { get; } = "5B7A7B4F-7419-4AA7-AE9E-41C5A996A343";

    }
}
